package com.lonwin.inspectionmanagement.mvp.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.lh.LhEarthSurfaceView;
import com.lh.LhSmoothEarthSurfaceView;
import com.lh.features.LhCoordinate;
import com.lh.layers.LhLayer;
import com.lh.layers.LhTiledImageLayer;
import com.lh.layers.imageLayers.TiandituImagesLayer;
import com.lh.layers.imageLayers.TiandituRoadsLayer;
import com.lonwin.inspectionmanagement.R;
import com.lonwin.inspectionmanagement.R2;
import com.lonwin.inspectionmanagement.app.AppConstants;
import com.lonwin.inspectionmanagement.app.service.LocationService;
import com.lonwin.inspectionmanagement.app.utils.AppUtil;
import com.lonwin.inspectionmanagement.app.utils.DataUtil;
import com.lonwin.inspectionmanagement.app.utils.LhEarthUtils;
import com.lonwin.inspectionmanagement.app.utils.TimeUtils;
import com.lonwin.inspectionmanagement.di.component.DaggerCruiseLocusComponent;
import com.lonwin.inspectionmanagement.di.module.CruiseLocusModule;
import com.lonwin.inspectionmanagement.mvp.contract.CruiseLocusContract;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.ConfigBean;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.DelLocusBean;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.HistoryRecordingBean;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.NeatentLocusBean;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.OpenLocusBean;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.PatrolBean;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.QuestListBean;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.SearLocusBean;
import com.lonwin.inspectionmanagement.mvp.presenter.CruiseLocusPresenter;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.jess.arms.utils.Preconditions.checkNotNull;
import com.hss01248.dialog.StyledDialog;
import com.hss01248.dialog.interfaces.MyDialogListener;
import com.hss01248.dialog.interfaces.MyItemDialogListener;
import com.lonwin.inspectionmanagement.widget.dialog.LoadingDailog;

public class CruiseLocusActivity extends BaseActivity<CruiseLocusPresenter> implements CruiseLocusContract.View {
    @BindView(R2.id.back_right_icon)
    TextView backRight;
    @BindView(R2.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R2.id.creaPointRecord_LhEarthSurfaceView)
    LhEarthSurfaceView creaPointRecordLhEarthSurfaceView;
    @BindView(R2.id.cruise_locus_xhlc_txt)
    TextView cruiseLocusXhlcTxt;
    @BindView(R2.id.cruise_locus_xhsc_txt)
    TextView cruiseLocusXhscTxt;
    @BindView(R2.id.cruise_locus_startTime_txt)
    TextView cruiseLocusStartTimeTxt;
    @BindView(R2.id.cruise_locus_endTime_txt)
    TextView cruiseLocusEndTimeTxt;
    @BindView(R2.id.cruise_locus_startAddress_txt)
    TextView cruiseLocusStartAddressTxt;
    @BindView(R2.id.cruise_locus_endAddress_txt)
    TextView cruiseLocusEndAddressTxt;

    @BindView(R2.id.cruise_locus_xhlc_name)
    TextView cruise_locus_xhlc_name;
    @BindView(R2.id.cruise_locus_xhlc_noname)
    TextView cruise_locus_xhlc_noname;
    @BindView(R2.id.cruise_locus_btn_txt)
    TextView cruise_locus_btn_txt;
     private Type model;
     private String gjid="";
     private  ConfigBean.RiverDatasBean.ChildrenBean childrenBean;
    private LoadingDailog loadingDailog;
    private SearLocusBean.DataBean mdataBean;
    public  enum Type implements Serializable {
        EDIT,PUB,ONE,LOOK
    }
    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerCruiseLocusComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .cruiseLocusModule(new CruiseLocusModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_cruise_locus; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        loadingDailog=new LoadingDailog.Builder(this).setMessage("处理中...").create();
        creaPointRecordLhEarthSurfaceView.getLayers().add(new TiandituRoadsLayer());
        creaPointRecordLhEarthSurfaceView.getLayers().add(new TiandituImagesLayer());
        //设置俯仰角
        creaPointRecordLhEarthSurfaceView.setTilt(1);
        //设置左右旋转角
        creaPointRecordLhEarthSurfaceView.setRotateAngle(0);
        //设置视野高度
        creaPointRecordLhEarthSurfaceView.setEyeDistance(3000);
        if (mPresenter.getConfigBean()!=null&&"532900000000000".equals(mPresenter.getConfigBean()))
        {
            //大理州的加上河湖图层
            LhLayer ly=new LhTiledImageLayer("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><Layer layerType=\"TiledImageLayer\" version=\"1\">	<DisplayName>dlRivers</DisplayName>	<DatasetName>dlRivers</DatasetName>	<DataCacheName>dlRivers</DataCacheName>	<Service serviceName=\"OGC:WMS\" version=\"1.3.0\">		<LayerNames>dlRivers</LayerNames>		<GetMapURL>http://120.55.185.135:8080/geoserver/DL/wms?service=WMS		</GetMapURL>		<GetCapabilitiesURL>http://120.55.185.135:8080/geoserver/DL/ows?SERVICE=WMS&amp;		</GetCapabilitiesURL>	</Service>	<FormatSuffix>.png</FormatSuffix>	<NumLevels count=\"19\" numEmpty=\"0\" />	<Sector>		<SouthWest>			<LatLon latitude=\"24.664255104162578\" longitude=\"98.86319237813336\"				units=\"degrees\" />		</SouthWest>		<NorthEast>			<LatLon latitude=\"26.75167320005819\" longitude=\"101.16379508157783\"				units=\"degrees\" />		</NorthEast>	</Sector>	<TileOrigin>		<LatLon latitude=\"-90.0\" longitude=\"-180.0\" units=\"degrees\" />	</TileOrigin>	<TileSize>		<Dimension height=\"512\" width=\"512\" />	</TileSize>	<LevelZeroTileDelta>		<LatLon latitude=\"36.0\" longitude=\"36.0\" units=\"degrees\" />	</LevelZeroTileDelta>	<ImageFormat>image/png</ImageFormat>	" +
                    "<UseTransparentTextures>true</UseTransparentTextures></Layer>","dl");
            creaPointRecordLhEarthSurfaceView.getLayers().add(ly);
        }
         if(getIntent()==null)
         {
             showMessage("数据异常");
             killMyself();
             return;
         }
        gjid = getIntent().getStringExtra(AppConstants.EXTRA_GJID);
          model=(CruiseLocusActivity.Type) getIntent().getSerializableExtra(AppConstants.EXTRA_INT);
          if (model==null)
          {
              showMessage("数据异常");
              killMyself();
              return;
          }
          switch (model)
          {
              case EDIT:
                  //未关联河湖的时候
                  backRight.setVisibility(View.VISIBLE);
                  backRight.setText("删除");
                  cruise_locus_xhlc_name.setVisibility(View.GONE);
                  cruise_locus_xhlc_noname.setVisibility(View.VISIBLE);
                  cruise_locus_btn_txt.setVisibility(View.VISIBLE);
                  cruise_locus_btn_txt.setText("保存");
                  backRight.setOnClickListener(new View.OnClickListener() {
                      @Override
                      public void onClick(View v) {
                          //删除
                          StyledDialog.buildIosAlert("提示", "你确定要删除该条记录吗？", new MyDialogListener() {
                              @Override
                              public void onFirst() {
                                  mPresenter.deleteXcpathTemp(gjid);
                              }

                              @Override
                              public void onSecond() {
                                  StyledDialog.dismiss();
                              }
                          }).show();
                      }
                  });
                  cruise_locus_xhlc_noname.setOnClickListener(new View.OnClickListener() {
                      @Override
                      public void onClick(View v) {
                          Intent intent = new Intent(CruiseLocusActivity.this, CruiseSearchActivity.class);
                          CruiseLocusActivity.this.startActivityForResult(intent, 1001);
                      }
                  });
                  cruise_locus_btn_txt.setOnClickListener(new View.OnClickListener() {
                      @Override
                      public void onClick(View v) {
                          if (childrenBean==null&&(mdataBean==null||mdataBean.getGroupnm()==null||TextUtils.isEmpty(mdataBean.getGroupnm())||mdataBean.getGroupid()==null||TextUtils.isEmpty(mdataBean.getGroupid())))
                          {
                              showMessage("请选择河湖");
                              return;
                          }
                          String temgroupName="";
                          String temgroupid="";
                          if (childrenBean!=null)
                          {
                              temgroupName=childrenBean.getName();
                               temgroupid=childrenBean.getId();
                          }else {
                              temgroupName=mdataBean.getGroupnm();
                              temgroupid=mdataBean.getGroupid();
                          }
                          mPresenter.neatenXcpathTemp(gjid,temgroupid,temgroupName);
                      }
                  });
                  break;
              case PUB:
                  //公开
//                  backRight.setVisibility(View.VISIBLE);
//                  backRight.setText("编辑");
                  cruise_locus_xhlc_name.setVisibility(View.VISIBLE);
                  cruise_locus_xhlc_noname.setVisibility(View.GONE);
                  cruise_locus_btn_txt.setVisibility(View.VISIBLE);
                  cruise_locus_btn_txt.setText("提交");
                  backRight.setOnClickListener(new View.OnClickListener() {
                      @Override
                      public void onClick(View v) {
                          //公开
//                          CruiseLocusActivity.startCruiseLocusActivity(CruiseLocusActivity.this,gjid,Type.EDIT,"整理轨迹");

                      }
                  });
                  cruise_locus_btn_txt.setOnClickListener(new View.OnClickListener() {
                      @Override
                      public void onClick(View v) {
                          StyledDialog.buildIosAlert("提示", "提交后"+mdataBean.getGroupnm()+"联系人可以查看到您的轨迹", new MyDialogListener() {
                              @Override
                              public void onFirst() {
                                  mPresenter.openXcpathTemp(gjid);
                              }

                              @Override
                              public void onSecond() {
                                  StyledDialog.dismiss();
                              }
                          }).show();

                      }
                  });

                  break;
              case ONE:
                  //公开
                  backRight.setVisibility(View.VISIBLE);
                  backRight.setText("删除");
                  cruise_locus_xhlc_name.setVisibility(View.VISIBLE);
                  cruise_locus_xhlc_noname.setVisibility(View.GONE);
                  cruise_locus_btn_txt.setVisibility(View.GONE);
//                  cruise_locus_btn_txt.setText("提交");
                  backRight.setOnClickListener(new View.OnClickListener() {
                      @Override
                      public void onClick(View v) {
                          StyledDialog.buildIosAlert("提示", "确定删除轨迹？", new MyDialogListener() {
                              @Override
                              public void onFirst() {
                                  mPresenter.deleteXcpathTemp(gjid);
                              }

                              @Override
                              public void onSecond() {
                                  StyledDialog.dismiss();
                              }
                          }).show();
                          //公开

                      }
                  });
                  cruise_locus_btn_txt.setOnClickListener(new View.OnClickListener() {
                      @Override
                      public void onClick(View v) {
                          mPresenter.openXcpathTemp(gjid);
                      }
                  });

                  break;
              case LOOK:
                  backRight.setVisibility(View.GONE);
                  cruise_locus_xhlc_name.setVisibility(View.VISIBLE);
                  cruise_locus_xhlc_noname.setVisibility(View.GONE);
                  cruise_locus_btn_txt.setVisibility(View.GONE);
                  break;
          }
        mPresenter.getXcpathTemp(gjid);
    }
    private void setTitle() {
        String title = getIntent().getStringExtra(AppConstants.EXTRA_STRING);
        if (!TextUtils.isEmpty(title)) {
            toolbarTitle.setText(title);
        }
    }
    @Override
    public void showLoading() {
        loadingDailog.show();
    }

    @Override
    public void hideLoading() {
        loadingDailog.dismiss();
    }

    @Override
    protected void onResume() {
        super.onResume();
        setTitle();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this,message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }


    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void queryHistorySucess(HistoryRecordingBean historyRecordingBean) {
        if (historyRecordingBean==null||historyRecordingBean.getTotal()<1)
        {
            showMessage("没有查询到巡河轨迹数据");
            return;
        }
       LhEarthUtils.drawCruiseLocus(creaPointRecordLhEarthSurfaceView,historyRecordingBean.getResult());
    }

    @Override
    public void getXcpathSuccess(PatrolBean patrolBean) {
        if (patrolBean==null||patrolBean.getData()==null)
        {
            showMessage("未获取到数据");
      //      startService(new Intent(this, LocationService.class));
            AppUtil.startService(this,new Intent(this, LocationService.class));

            return;
        }
        mPresenter.queryHistory(patrolBean.getData().getStarttm(),patrolBean.getData().getEndtm(),1);
        cruiseLocusXhlcTxt.setText(String.valueOf(patrolBean.getData().getKm()));
         cruiseLocusXhscTxt.setText(patrolBean.getData().getTm());
        cruiseLocusStartTimeTxt.setText(patrolBean.getData().getStarttm());
        cruiseLocusEndTimeTxt.setText(patrolBean.getData().getEndtm());
        cruiseLocusStartAddressTxt.setText(patrolBean.getData().getStartaddr());
        cruiseLocusEndAddressTxt.setText(patrolBean.getData().getEndaddr());

    }

    @Override
    public void getXcpathTempSuccess(SearLocusBean.DataBean dataBean) {
        mdataBean=dataBean;
        if (dataBean.getNeatenflag()!=0)
        {
            //标识已经关联了河湖
            cruise_locus_xhlc_name.setText(dataBean.getGroupnm()!=null?dataBean.getGroupnm():"");
            cruise_locus_xhlc_noname.setText(dataBean.getGroupnm()!=null?dataBean.getGroupnm():"");
            //关联了河湖才查询问题点
            mPresenter.getGcglQuestTemp(dataBean.getGjid());
        }

        cruiseLocusXhlcTxt.setText(String.valueOf(dataBean.getKm())+" 米");
        cruiseLocusXhscTxt.setText(DataUtil.formtTime_new(Integer.parseInt(dataBean.getTm())));
        cruiseLocusStartTimeTxt.setText(TimeUtils.dateForStr(dataBean.getStarttm()).substring(5,16));
        cruiseLocusEndTimeTxt.setText(TimeUtils.dateForStr(dataBean.getEndtm()).substring(5,16));
        cruiseLocusStartAddressTxt.setText(dataBean.getStartaddr());
        cruiseLocusEndAddressTxt.setText(dataBean.getEndaddr());
        cruise_locus_xhlc_name.setText(dataBean.getGroupnm()!=null?dataBean.getGroupnm():"");
        LhEarthUtils.drawCruiseLocusNew(creaPointRecordLhEarthSurfaceView,dataBean.getGpsPoints());

    }

    @Override
    public void neatenXcpathTempSuccess(NeatentLocusBean.DataBean dataBean) {
        killMyself();
    }

    @Override
    public void openXcpathTempSuccess(OpenLocusBean.DataBean dataBean) {
            killMyself();
    }

    @Override
    public void deleteXcpathTempSuccess(DelLocusBean delLocusBean) {
        Intent intent=new Intent();
        intent.putExtra("DelLocusBean",delLocusBean);
        setResult(RESULT_OK,intent);
         killMyself();
    }

    @Override
    public void getGcglQuestTempSuccess(List<QuestListBean.DataBean> dataBeans) {
        //绘制问题点
        LhEarthUtils.drawQuestPoint(creaPointRecordLhEarthSurfaceView,dataBeans);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
    @Subscriber(mode = ThreadMode.MAIN)
    public void reciverLocation(AMapLocation aMapLocation) {
        EventBus.getDefault().unregister(this);
        //接收到定位信息
        LhEarthUtils.locatPosition(creaPointRecordLhEarthSurfaceView, LhCoordinate.fromDegrees(aMapLocation.getLatitude(), aMapLocation.getLongitude()));//25.07263654159436,102.66734565340529

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data==null)
        {
            return;
        }
        if (requestCode == 1001) {
            childrenBean = (ConfigBean.RiverDatasBean.ChildrenBean) data.getSerializableExtra("ChildrenBean");
            cruise_locus_xhlc_noname.setText(childrenBean.getName());
        }else if (requestCode==1011){
            //删除情况就直接返回了
          killMyself();
        }
    }

    /**
     * @param context
     * @param mode    必须
     * @param title
     */
    public static void startCruiseLocusActivity(Context context, String id, CruiseLocusActivity.Type mode, String title) {
        Intent intent = new Intent(context, CruiseLocusActivity.class);
        intent.putExtra(AppConstants.EXTRA_GJID, id);
        intent.putExtra(AppConstants.EXTRA_INT, mode);
        intent.putExtra(AppConstants.EXTRA_STRING, title);
        if (mode==Type.EDIT)
        {
            ((Activity)context).startActivityForResult(intent,1011);
        }else {
            context.startActivity(intent);
        }

    }
}
